package com.example.mymvvmdemo.models.sms_code;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.lifecycle.ViewModelProvider;

import com.example.mymvvmdemo.R;
import com.example.mymvvmdemo.base.BaseLoadActivity;
import com.example.mymvvmdemo.constants.UrlConstants;
import com.example.mymvvmdemo.constants.UrlTypeConstants;
import com.example.mymvvmdemo.databinding.ActivitySmsCodeBinding;
import com.example.mymvvmdemo.dialog.LoadingAnimDialog;
import com.example.mymvvmdemo.models.register.RegisterActivity;
import com.example.mymvvmdemo.models.sms_code.entity.SendCodeEntity;
import com.example.mymvvmdemo.net.presenter.PostBodyPresenter;
import com.example.mymvvmdemo.net.view.IView;
import com.example.mymvvmdemo.utils.StrUtils;
import com.example.mymvvmdemo.utils.ToastUtils;

import java.util.HashMap;

public class SmsCodeActivity extends BaseLoadActivity<ActivitySmsCodeBinding> implements View.OnClickListener, IView.PostBodyView {

    public static void startSmsCodeActivity(Activity activity, String type, String account) {
        Intent intent = new Intent(activity, SmsCodeActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("account", account);
        activity.startActivity(intent);
    }

    private SmsCodeViewModel viewModel;
    private PostBodyPresenter postBodyPresenter;

    /*** 加载时候的Dialog */
    private LoadingAnimDialog loadingDialog;

    @Override
    protected void showDialog() {
        if (loadingDialog == null)
            loadingDialog = new LoadingAnimDialog(this, getResources().getString(R.string.load));
        if (!loadingDialog.isShowing()) loadingDialog.show(this);
    }

    @Override
    protected void dismissDialog() {
        if (loadingDialog != null && loadingDialog.isShowing()) {
            loadingDialog.close(this);
        }
    }


    @Override
    protected void initData() {
        viewModel = new ViewModelProvider(this).get(SmsCodeViewModel.class);
        postBodyPresenter = new PostBodyPresenter(this);
        viewModel.type = getIntent().getStringExtra("type");
        viewModel.account = getIntent().getStringExtra("account");
        initShowView();
        uiHandler.sendEmptyMessageDelayed(viewModel.HANDLER_SEND_SMS, viewModel.HANDLER_SEND_SMS_TIME);

    }

    @Override
    protected void initListener() {
        binding.include.ivBack.setOnClickListener(this);
        binding.tvResend.setOnClickListener(this);
        binding.tvNext.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_resend:
                reSendCode();
                break;
            case R.id.tv_next:
                String passString = binding.codeLayout.getPassString();
                if (passString.length() < 6) {
                    toast(R.string.input_sms_code, ToastUtils.TOA_W);
                    return;
                }
                viewModel.startSetPasswordActivity(this, viewModel.type, viewModel.account, passString);
                break;
            default:
                break;
        }
    }

    /************************************Handler********************************************/
    public Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == viewModel.HANDLER_SEND_SMS) {
                viewModel.timeCount--;
                if (viewModel.timeCount >= 0) {
                    uiHandler.sendEmptyMessageDelayed(viewModel.HANDLER_SEND_SMS, viewModel.HANDLER_SEND_SMS_TIME);
                    binding.tvResend.setText(getString(R.string.sms_resend) + "(" + viewModel.timeCount + ")");
                } else {
                    viewModel.timeCount = 60;
                    binding.tvResend.setText(getString(R.string.sms_resend));
                    binding.tvResend.setEnabled(true);
                    binding.tvResend.setTextColor(getResources().getColor(R.color.black_two));
                }
            }

        }
    };

    /************************************自定义方法********************************************/
    private void initShowView() {
        if (!StrUtils.isEmpty(viewModel.account)) {
            binding.tvEmail.setText(viewModel.account);
        }
    }

    private void sendCodeSuccessUI() {
        binding.tvResend.setEnabled(false);
        binding.tvResend.setTextColor(getResources().getColor(R.color.gray_three));
        uiHandler.sendEmptyMessageDelayed(viewModel.HANDLER_SEND_SMS, viewModel.HANDLER_SEND_SMS_TIME);
    }

    private void reSendCode() {
        if (viewModel.account.contains("@")) {
            //发送邮箱验证码
            startLoadSendEmail(viewModel.account);
        } else {
            //发送手机号验证码
            startLoadSendSms(viewModel.account);
        }
    }

    private void startLoadSendEmail(String account) {
        showDialog();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("email", account);
        postBodyPresenter.startLoadPostBody(UrlConstants.sendEmailCode, hashMap, UrlTypeConstants.sendEmailCode);
    }

    public void startLoadSendSms(String account) {
        showDialog();
        HashMap<String, String> hashMap = new HashMap<>();
        hashMap.put("mobile", account);
        postBodyPresenter.startLoadPostBody(UrlConstants.sendSmsCode, hashMap, UrlTypeConstants.sendSmsCode);
    }


    /**************************v**********数据请求回调****************************************/
    @Override
    public void loadPostBodySuccess(String result, String type, int code) {
        if (type.equals(UrlTypeConstants.sendEmailCode)) {
            loadSendEmailCodeSuccess(result);
        } else if (type.equals(UrlTypeConstants.sendSmsCode)) {
            loadSendSmsCodeSuccess(result);
        }
    }

    @Override
    public void loadPostBodyFail(String message, String type) {
        if (type.equals(UrlTypeConstants.sendEmailCode)) {
            loadSendEmailCodeFail();
        } else if (type.equals(UrlTypeConstants.sendSmsCode)) {
            loadSendSmsCodeFail();
        }
    }

    @Override
    public void loadPostBodyAccountError(int code) {

    }

    @Override
    public void loadPostBodyNetWorkError(String type) {
        dismissDialog();
        toast(R.string.network_error, ToastUtils.TOA_W);
    }

    /************************************处理请求后数据***************************************/
    private void loadSendSmsCodeSuccess(String result) {
        dismissDialog();

        SendCodeEntity sendCodeEntity = gson.fromJson(result, SendCodeEntity.class);
        int code = sendCodeEntity.getCode();
        if (code != 200) {
            String message = sendCodeEntity.getData().getMessage();
            toast(message, ToastUtils.TOA_W);
            return;
        }
        sendCodeSuccessUI();
    }

    private void loadSendSmsCodeFail() {
        dismissDialog();
        toast(R.string.send_code_error, ToastUtils.TOA_W);
    }

    private void loadSendEmailCodeSuccess(String result) {
        dismissDialog();
        SendCodeEntity sendCodeEntity = gson.fromJson(result, SendCodeEntity.class);
        int code = sendCodeEntity.getCode();
        if (code != 200) {
            String message = sendCodeEntity.getData().getMessage();
            toast(message, ToastUtils.TOA_W);
            return;
        }
        sendCodeSuccessUI();

    }

    private void loadSendEmailCodeFail() {
        dismissDialog();
        toast(R.string.send_code_error, ToastUtils.TOA_W);
    }

}